/*global self, pi, postMessage */

/**
 * 加载线程：从磁盘中加载数据
 * 消息种类：
 * 1. 加载消息：
 *	{
 *		type: "load",
 *		id: 代表该请求的唯一数字,
 *		data: 文件的vfs路径
 *	}
 *	返回：
 *	{
 *		type: "load",
 *		id: 代表该请求的唯一数字,
 *		data: 成功{size:数据字节数,data:内存句柄}; 失败{error:, reason:}
 *	}
 */
pi.mod.define('pi.worker.load', function (pi) {
	"use strict";
	var module = {};
	module.init = function () {
		var table = {}; /* 处理加载消息 */
		table.load = function (path) {
			var r, s, h, err, file;
			if (!pi.lang.isString(path)) {
				r = {
					error: 3,
					reason: "load worker, load, path isn't string"
				};
			} else {
				file = pi.vfs.openFile(path, pi.vfs.FILE_OPEN_READ);
				if (file === 0) {
					err = pi.vfs.getError();
					r = {
						error: 4,
						reason: "path = " + path + ", " + err.msg
					};
				} else {
					s = pi.vfs.getFileSize(file);
					if (s > 0) {
						h = pi.vfs.readFileMem(file, 0, false, s);
					} else {
						err = pi.vfs.getError();
						r = {
							error: 5,
							reason: "path = " + path + ", " + err.msg
						};
					}
					pi.vfs.closeFile(file);
				}
			}
			if (r === undefined) {
				r = {
					data: h,
					size: s
				};
			}
			return r;
		};
		return table;
	};

	module.onmessage = function (e) {
		var fun, res = 0,
			req = e.data;
		if (req === "quit") {
			self.close();
		} else if (pi.lang.isObject(req)) {
			if (module.methodTable === undefined) {
				module.methodTable = module.init();
			}
			if (module.methodTable && req.type) {
				fun = module.methodTable[req.type];
				if (fun !== undefined) {
					res = fun(req.data);
				} else {
					res = {
						error: 2,
						reason: "load worker, type isn't function name"
					};
				}
			} else {
				res = {
					error: 1,
					reason: "load worker, slef.methodTable && req.type"
				};
			}
			postMessage({
				type: req.type,
				id: req.id,
				data: res
			});
		}
	};
	return module;
});